<template>
  <div class="article-detail-container animate__animated animate__fadeIn">
    <!-- 文章标题 -->
    <div class="article-header animate__animated animate__fadeInDown">
      <h1 class="article-title">{{ article.title }}</h1>
      <p class="article-description">{{ article.description }}</p>
    </div>

    <!-- 作者信息 -->
    <div class="author-info animate__animated animate__fadeIn">
      <div class="author-basic">
        <el-popover
          placement="right"
          trigger="hover"
          width="300"
        >
          <template #reference>
            <div class="author-avatar" @click="router.push(`/home/userCenter/${author.id}`)">
              <img :src="author.profilePicture || defaultAvatar" alt="avatar">
            </div>
          </template>
          <div class="author-card">
            <div class="author-card-header">
              <img :src="author.profilePicture || defaultAvatar" alt="avatar">
              <h3>{{ author.username }}</h3>
            </div>
            <div class="author-card-info">
              <p>{{ author.description || '这个人很懒，什么都没留下' }}</p>
            </div>
            <div class="author-card-stats">
              <div class="stat-item">
                <span class="stat-label">文章</span>
                <span class="stat-value">{{ author.articleCount }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">获赞</span>
                <span class="stat-value">{{ author.likeCount }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">粉丝</span>
                <span class="stat-value">{{ author.followerCount }}</span>
              </div>
            </div>
          </div>
        </el-popover>
          <span 
            class="author-name username-hover" 
            @click="router.push(`/home/userCenter/${author.id}`)"
          >{{ author.username }}</span>
          <p style="color: #606266;">{{ author.description || '这个人很懒，什么都没留下' }}</p>
      </div>
      <el-button 
        v-if="author.id && profile.id 
        && 
        author.id !== profile.id" 
        class="follow-btn" 
        type="text" 
        size="small" 
        round 
        :class="{ active: isFollowed, 'gray-background': isFollowed}" 
        @click="handleFollow"
      >
        {{ isFollowed ? '取消关注' : '关注' }}
      </el-button>
    </div>

    <!-- 文章内容 -->
    <div class="article-content-wrapper animate__animated animate__fadeIn">
      <div class="article-content" v-html="article.content"></div>
    </div>

    <!-- 文章元信息 -->
    <div class="article-meta animate__animated animate__fadeInUp">
      <div class="meta-item">
        <t-icon name="time" />
        <span>发布于: {{ formatDate(article.createdAt) }}</span>
      </div>
      <div class="meta-item">
        <t-icon name="edit-1" />
        <span>更新于: {{ formatDate(article.updatedAt) }}</span>
      </div>
      <div class="meta-item">
        <t-icon name="check-circle" />
        <span>状态: {{ article.status }}</span>
      </div>
    </div>

    <!-- 互动区域 -->
    <div class="interaction-area">
      <!-- 点赞收藏 -->
      <div class="action-buttons animate__animated animate__fadeInUp">
        <button class="action-btn like-btn" :class="{ active: isLiked }" :disabled="isLiking" @click="handleLike">
          <!-- 正常状态显示点赞图标 -->
          <t-icon name="thumb-up" :class="{ active: isLiked }" v-if="!isLiking" /> 
          <!-- 加载状态显示加载动画图标 -->
          <t-icon name="loading" spin v-if="isLiking" /> 
          <span>{{ article.likeCount || 0 }}</span>
        </button>
        <el-popover
          placement="top"
          :width="300"
          trigger="click"
          v-model:visible="showFolders"
        >
          <template #reference>
            <button class="action-btn favorite-btn" :class="{ active: isFavorited }">
              <t-icon name="star" :class="{ active: isFavorited }" />
              <span>{{ article.favoriteCount || 0 }}</span>
            </button>
          </template>
          <div class="folder-list">
            <h4>选择收藏夹</h4>
            <ul>
              <li v-for="folder in favoriteFolders" :key="folder.id" class="folder-item">
                <span>{{ folder.folderName }} ({{ folder.contentCount }})</span>
                <el-button 
                  size="small"
                  :type="folder.isFavorited ? 'warning' : 'default'"
                  @click="handleFavorite(folder.id)"
                >
                <span v-if="!isFavoriteFoldersLoading">{{ folder.isFavorited ? '取消收藏' : '收藏' }}</span>
                <t-icon name="loading" v-else spin /> <!-- 加载中的图标 -->
                </el-button>
              </li>
            </ul>
          </div>
        </el-popover>
      </div>

      <!-- 评论区 -->
      <div class="comments-section" v-if="showComments">
        <div class="comments-header">
          <h3 class="comments-title"><t-icon name="chat" /> 评论 ({{ article.commentCount || 0 }})</h3>
          
          <div class="sort-switch">
            <span :class="{ active: !commentSortDesc }" @click="commentSortDesc = false; handleSortChange()">最早</span>
            <span :class="{ active: commentSortDesc }" @click="commentSortDesc = true; handleSortChange()">最新</span>
          </div>
        </div>
        
        <!-- 编辑器区域 -->
        <div class="editor-container">
          <div class="editor-wrapper">
            <Toolbar
              style="border-bottom: 1px solid #dcdfe6"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 200px; overflow-y: hidden;"
              v-model="newComment"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleCreated"
            />
          </div>
          <button class="submit-comment" @click="submitComment">
            <t-icon name="send" /> 发表评论
          </button>
        </div>

        <div id="comments-container" v-if="comments.length > 0">
          <div v-for="comment in comments" :key="comment.id" class="comment-item">
            <div class="user-info">
              <el-popover
              placement="right"
              trigger="hover"
              width="300"
              :content="commentPopoverContent"
              :disabled="!comment.user"
              >
                <template #reference>
                  <img :src="comment.user?.profilePicture || defaultAvatar" alt="avatar" class="comment-avatar" @click="router.push(`/home/userCenter/${comment.user.id}`)" style="cursor: pointer;">
                </template>
                <div class="author-card">
                  <div class="author-card-header">
                    <img :src="comment.user?.profilePicture || defaultAvatar" alt="avatar">
                    <h3>{{ comment.user?.username }}</h3>
                  </div>
                  <div class="author-card-info">
                    <p>{{ comment.user?.description || '这个人很懒，什么都没留下' }}</p>
                  </div>
                  <div class="author-card-stats">
                    <div class="stat-item">
                      <span class="stat-label">文章</span>
                      <span class="stat-value">{{ comment.user?.articleCount || 0 }}</span>
                    </div>
                    <div class="stat-item">
                      <span class="stat-label">获赞</span>
                      <span class="stat-value">{{ comment.user?.likeCount || 0 }}</span>
                    </div>
                    <div class="stat-item">
                      <span class="stat-label">粉丝</span>
                      <span class="stat-value">{{ comment.user?.followerCount || 0 }}</span>
                    </div>
                  </div>
                </div>
              </el-popover>
              <div>
                <div 
                  class="user-name username-hover" 
                  @click="router.push(`/home/userCenter/${comment.user.id}`)"
                >
                  {{ comment.user?.username }}
                </div>
                
              </div>
            </div>
            <div class="comment-content" v-html="comment.content"></div>
            <div class="comment-footer">
              <div class="time">{{ formatDate(comment.createdAt) }}</div>
              <div class="comment-actions">
                <button class="action-button" :disabled="comment.isLiking" @click="handleCommentLike(comment)">
                  <!-- 正常状态显示点赞图标 -->
                  <t-icon 
                    name="thumb-up" 
                    :class="{ active: comment.isLiked }" 
                    v-if="!comment.isLiking"
                  />
                  <!-- 加载状态显示加载动画图标 -->
                  <t-icon name="loading" spin v-if="comment.isLiking" /> 
                  <span>{{ comment.likeCount || 0 }}</span>
                </button>
                <button class="action-button" @click="replyToComment(comment)">
                  <t-icon name="chat" />
                  <span>回复</span>
                </button>
              </div>
            </div>
            
            <!-- 回复区域 -->
            <div class="replies" v-if="comment.commentCount > 0">
              <button class="toggle-replies" @click="toggleReplies(comment)">
                {{ comment.commentCount }}条回复 {{ comment.showReplies ? '▼' : '▶' }}
              </button>
              <div class="replies-container" v-if="comment.showReplies">
                <div v-for="reply in comment.replies" :key="reply.id" class="reply-item">
                  <div class="user-info">
                    <el-popover
                    placement="right"
                    trigger="hover"
                    width="300"
                    :content="replyPopoverContent"
                    :disabled="!reply.user"
                    >
                      <template #reference>
                        <img :src="reply.user?.profilePicture || defaultAvatar" alt="avatar" class="reply-avatar" @click="router.push(`/home/userCenter/${reply.user.id}`)" style="cursor: pointer;">
                      </template>
                      <div class="author-card">
                        <div class="author-card-header">
                          <img :src="reply.user?.profilePicture || defaultAvatar" alt="avatar">
                          <h3>{{ reply.user?.username }}</h3>
                        </div>
                        <div class="author-card-info">
                          <p>{{ reply.user?.description || '这个人很懒，什么都没留下' }}</p>
                        </div>
                        <div class="author-card-stats">
                          <div class="stat-item">
                            <span class="stat-label">文章</span>
                            <span class="stat-value">{{ reply.user?.articleCount || 0 }}</span>
                          </div>
                          <div class="stat-item">
                            <span class="stat-label">获赞</span>
                            <span class="stat-value">{{ reply.user?.likeCount || 0 }}</span>
                          </div>
                          <div class="stat-item">
                            <span class="stat-label">粉丝</span>
                            <span class="stat-value">{{ reply.user?.followerCount || 0 }}</span>
                          </div>
                        </div>
                      </div>
                    </el-popover>
                    <div>
                      <div 
                        class="user-name username-hover" 
                        @click="router.push(`/home/userCenter/${reply.user.id}`)"
                      >
                        {{ reply.user?.username }} 
                      </div> 
                      <span class="reply-to">回复</span> 
                      <span 
                        class="replied-username username-hover" 
                        @click="router.push(`/home/userCenter/${reply.repliedUserId}`)"
                      >
                        @{{ reply.repliedUsername }}
                      </span>
                    </div>
                  </div>
                  <div class="comment-content" v-html="reply.content"></div>
                  <div class="comment-footer">
                    <div class="time">{{ formatDate(reply.createdAt) }}</div>
                    <div class="comment-actions">
                      <button class="action-button" :disabled="reply.isLiking" @click="handleReplyLike(reply)">
                        <!-- 正常状态显示点赞图标 -->
                        <t-icon 
                          name="thumb-up" 
                          :class="{ active: reply.isLiked }" 
                          v-if="!reply.isLiking"
                        />
                        <!-- 加载状态显示加载动画图标 -->
                        <t-icon name="loading" spin v-if="reply.isLiking" /> 
                        <span>{{ reply.likeCount || 0 }}</span>
                      </button>
                      <button class="action-button" @click="replyToReply(reply, comment)">
                        <t-icon name="chat" />
                        <span>回复</span>
                      </button>
                    </div>
                  </div>
                </div>
                <button class="load-more" v-if="comment.hasMoreReplies" @click="loadMoreReplies(comment)">
                  查看更多回复
                </button>
              </div>
            </div>
          </div>
          
          <button class="load-more" v-if="hasMore" @click="loadMoreComments">
            查看更多评论
          </button>
        </div>
        
        <div v-else class="no-comments">
          <p>暂无评论，来发表第一条评论吧！</p>
        </div>
      </div>
    </div>

    <!-- 悬浮按钮 -->
    <div class="float-buttons">
      <button class="float-btn" @click="scrollToTop" title="回到顶部">
        <t-icon name="chevron-up" />
      </button>
      <button class="float-btn" @click="scrollToBottom" title="到达底部">
        <t-icon name="chevron-down" />
      </button>
    </div>

    <!-- 回复弹窗 -->
    <el-dialog
      v-model="replyDialogVisible"
      title="发表回复"
      width="50%"
      :before-close="closeReplyDialog"
    >
      <div class="reply-dialog-content">
        <div class="reply-target-info" v-if="currentReplyTarget">
          <span>回复给: </span>
          <span 
            class="reply-target-name username-hover" 
            @click="router.push(`/home/userCenter/${currentReplyTarget.id}`)"
          >
            @{{ currentReplyTarget.username }}
          </span>
        </div>
        <div class="reply-editor-wrapper">
          <Toolbar
            style="border-bottom: 1px solid #dcdfe6"
            :editor="replyEditorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
          />
          <Editor
            style="height: 200px; overflow-y: hidden;"
            v-model="replyContent"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="handleReplyEditorCreated"
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeReplyDialog">取消</el-button>
          <el-button type="primary" @click="submitReplyFromDialog">
            <t-icon name="send" /> 发表回复
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>

  
</template>
<script setup>
import { ref, onMounted, shallowRef } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { findArticleById } from '@/api/articleApi';
import { findUserById, createUserLike, deleteUserLike, isLiked as checkIsLiked, 
         createUserFavorite, deleteUserFavorite, isFavorite as checkIsFavorite,
         followUser, unfollowUser, isFollowing as checkIsFollowing,
         getAllFavoriteFolders, isFolderFavorite } from '@/api/userApi';
import { getCommentsByParentIdASC, getCommentsByParentIdDESC, uploadComment } from '@/api/commentApi';
import { ElCard, ElMessage, ElSwitch } from 'element-plus';
import { useUserStore } from '@/stores/userStore';
import { storeToRefs } from 'pinia';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';
import { uploadImage} from '@/api/uploadApi';
import 'animate.css';
import defaultAvatarImg from '@/imgs/avatar.png';
// 文章点赞加载状态
const isLiking = ref(false);
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
const replyEditorRef = shallowRef();
const router = useRouter();
const route = useRoute();
// 编辑器配置
const toolbarConfig = {
  toolbarKeys: [
    'bold',
    'italic',
    'underline',
    'through',
    'color',
    'bgColor',
    'fontSize',
    'fontFamily',
    'bulletedList',
    'numberedList',
    'justifyLeft',
    'justifyCenter',
    'justifyRight',
    'emotion',
    'uploadImage',
    'undo',
    'redo'
  ]
};

const editorConfig = {
  placeholder: '写下你的评论...',
  autoFocus: false,
  MENU_CONF: {
    uploadImage: {
      customUpload: async (file, insertFn) => {
        const formData = new FormData();
        formData.append('file', file);

        try {
          const response = await uploadImage(formData);
      
          insertFn(response.data.url);
          ElMessage({
            message: "图片上传成功",
            type: 'success',
          });
          
        } catch (error) {
          console.error('图片上传出错:', error);
          ElMessage({
            message: "图片上传出错",
            type: 'error',
          });
        }
      }
    }
  }
};

const mode = 'default';

const handleCreated = (editor) => {
  editorRef.value = editor;
};

const handleReplyEditorCreated = (editor) => {
  replyEditorRef.value = editor;
};

const userStore = useUserStore();
const { profile } = storeToRefs(userStore);

const articleId = ref(route.params.id);
const isLiked = ref(false);
const isFavorited = ref(false);
const isFollowed = ref(false);
const showFolders = ref(false);
const favoriteFolders = ref([]);
const showComments = ref(true);
const comments = ref([]);
const newComment = ref('');
const commentSortDesc = ref(false);
const currentPage = ref(1);
const pageSize = ref(5);
const hasMore = ref(false);
const isFavoriteFoldersLoading = ref(false); // 新增：表示收藏夹列表是否正在加载
// 回复弹窗相关
const replyDialogVisible = ref(false);
const replyContent = ref('');
const currentReplyTarget = ref(null);
const currentParentComment = ref(null);

const defaultAvatar = defaultAvatarImg;

const article = ref({
  id: '',
  title: '',
  content: '',
  description: '',
  userId: null,
  status: '',
  createdAt: null,
  updatedAt: null,
  likeCount: 0,
  favoriteCount: 0,
  commentCount: 0
});

const author = ref({
  id: null,
  username: '',
  profilePicture: '',
  articleCount: 0,
  likeCount: 0,
  followerCount: 0
});

const formatDate = (dateString) => {
  if (!dateString) return '';
  
  const date = new Date(dateString);
  const now = new Date();
  const diff = now - date;
  
  // 如果是当前分钟内
  if (diff < 60 * 1000) {
    const seconds = Math.floor(diff / 1000);
    return `${seconds}秒前`;
  }
  
  // 如果是当前小时内
  if (diff < 60 * 60 * 1000) {
    const minutes = Math.floor(diff / (60 * 1000));
    return `${minutes}分钟前`;
  }
  
  // 如果是当天
  if (diff < 24 * 60 * 60 * 1000) {
    const hours = Math.floor(diff / (60 * 60 * 1000));
    return `${hours}小时前`;
  }
  
  // 如果是今年
  if (date.getFullYear() === now.getFullYear()) {
    return `${date.getMonth() + 1}月${date.getDate()}日`;
  }
  
  // 如果是往年
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
};

const loadComments = async (reset = false) => {
  try {
    if (reset) {
      currentPage.value = 1;
      comments.value = [];
    }
    
    const getComments = commentSortDesc.value ? getCommentsByParentIdDESC : getCommentsByParentIdASC;
    const response = await getComments(article.value.id, currentPage.value, pageSize.value);
    
    const { data, total } = response;
    
    // 获取每个评论的用户信息
    const commentsWithUserInfo = await Promise.all(
      data.map(async (comment) => {
        try {
          const userResponse = await findUserById(comment.userId);
          
          // 检查当前用户是否点赞了该评论
          let isLiked = false;
          if (profile.value.id) {
            const likeResponse = await checkIsLiked(profile.value.id, comment.id, 'comment');
            isLiked = likeResponse.data;
          }
          
          return {
            ...comment,
            user: userResponse.data,
            isLiked,
            showReplies: false,
            replies: [],
            currentReplyPage: 1,
            hasMoreReplies: false,
            // 新增：评论点赞加载状态
            isLiking: false 
          };
        } catch (error) {
          console.error('获取评论用户信息失败:', error);
          return {
            ...comment,
            user: { username: '未知用户', profilePicture: '' },
            isLiked: false,
            showReplies: false,
            replies: [],
            currentReplyPage: 1,
            hasMoreReplies: false,
            // 新增：评论点赞加载状态
            isLiking: false 
          };
        }
      })
    );
    
    comments.value = reset ? commentsWithUserInfo : [...comments.value, ...commentsWithUserInfo];
    hasMore.value = comments.value.length < total;
  } catch (error) {
    console.error('获取评论失败:', error);
    ElMessage.error('获取评论失败');
  }
};

const loadReplies = async (comment, reset = false) => {
  try {
    if (reset) {
      comment.currentReplyPage = 1;
      comment.replies = [];
    }
    
    const getComments = commentSortDesc.value ? getCommentsByParentIdDESC : getCommentsByParentIdASC;
    const response = await getComments(comment.id, comment.currentReplyPage, pageSize.value);
    
    const { data, total } = response;
    
    // 获取每个回复的用户信息
    const repliesWithUserInfo = await Promise.all(
      data.map(async (reply) => {
        try {
          const userResponse = await findUserById(reply.userId);
          
          // 检查当前用户是否点赞了该回复
          let isLiked = false;
          if (profile.value.id) {
            const likeResponse = await checkIsLiked(profile.value.id, reply.id, 'comment');
            isLiked = likeResponse.data;
          }
          
          return {
            ...reply,
            user: userResponse.data,
            isLiked,
            // 新增：回复点赞加载状态
            isLiking: false 
          };
        } catch (error) {
          console.error('获取回复用户信息失败:', error);
          return {
            ...reply,
            user: { username: '未知用户', profilePicture: '' },
            isLiked: false,
            // 新增：回复点赞加载状态
            isLiking: false 
          };
        }
      })
    );
    
    comment.replies = reset ? repliesWithUserInfo : [...comment.replies, ...repliesWithUserInfo];
    comment.hasMoreReplies = comment.replies.length < total;
  } catch (error) {
    console.error('获取回复失败:', error);
    ElMessage.error('获取回复失败');
  }
};

const handleComment = async () => {
  showComments.value = !showComments.value;
  if (showComments.value && comments.value.length === 0) {
    await loadComments();
  }
};

const handleSortChange = async () => {
  await loadComments(true);
};

const loadMoreComments = async () => {
  currentPage.value++;
  await loadComments();
};

const loadMoreReplies = async (comment) => {
  comment.currentReplyPage++;
  await loadReplies(comment);
};

const toggleReplies = async (comment) => {
  comment.showReplies = !comment.showReplies;
  
  if (comment.showReplies && comment.replies.length === 0) {
    await loadReplies(comment, true);
  }
};

const replyToComment = (comment) => {
  currentReplyTarget.value = comment.user;
  currentParentComment.value = comment;
  replyContent.value = `@${comment.user.username} `;
  replyDialogVisible.value = true;
  
  // 如果回复列表为空，加载回复
  if (comment.replies.length === 0) {
    loadReplies(comment, true);
  }
};

const replyToReply = (reply, comment) => {
  currentReplyTarget.value = reply.user;
  currentParentComment.value = comment;
  replyContent.value = `@${reply.user.username} `;
  replyDialogVisible.value = true;
};

const closeReplyDialog = () => {
  replyDialogVisible.value = false;
  replyContent.value = '';
  currentReplyTarget.value = null;
  currentParentComment.value = null;
};

const submitComment = async () => {
  if (!profile.value?.id) {
    ElMessage.warning('请先登录');
    return;
  }

  if (!newComment.value.trim()) {
    ElMessage.warning('评论内容不能为空');
    return;
  }

  try {
    const commentData = {
      content: newComment.value,
      userId: profile.value.id,
      parentId: article.value.id,
      contentType: 'article',
      repliedUsername: author.value.username,
      repliedUserId: author.value.id
    };

    const response = await uploadComment(commentData);
    
    newComment.value = '';
    article.value.commentCount++;
    await loadComments(true);
    // 新增：强制设置为最新排序
    commentSortDesc.value = true;
      
      // 新增：触发排序更新
      await handleSortChange();
    ElMessage.success('评论发表成功');
    
  } catch (error) {
    console.error('提交评论出错:', error);
    ElMessage.error('评论发表失败，请稍后重试');
  }
};

const submitReplyFromDialog = async () => {
  if (!profile.value?.id) {
    ElMessage.warning('请先登录');
    return;
  }

  if (!replyContent.value.trim()) {
    ElMessage.warning('回复内容不能为空');
    return;
  }

  if (!currentParentComment.value) {
    ElMessage.warning('回复目标不存在');
    return;
  }

  try {
    const replyData = {
      content: replyContent.value,
      userId: profile.value.id,
      parentId: currentParentComment.value.id,
      contentType: 'comment',
      repliedUsername: currentReplyTarget.value.username,
      repliedUserId: currentReplyTarget.value.id
    };

    const response = await uploadComment(replyData);
    
    
    closeReplyDialog();
    // currentParentComment.value.commentCount++;
    
    // // 如果回复区域已经展开，则刷新回复列表
    // if (currentParentComment.value.showReplies) {
    //   await loadReplies(currentParentComment.value, true);
    // } else {
    //   // 如果回复区域未展开，则展开并加载回复
    //   currentParentComment.value.showReplies = true;
    //   await loadReplies(currentParentComment.value, true);
    // }
      
      ElMessage.success('回复发表成功');
    
  } catch (error) {
    console.error('提交回复出错:', error);
    ElMessage.error('回复发表失败，请稍后重试');
  }
};

const handleCommentLike = async (comment) => {
  // 如果正在加载，直接返回，防止重复点击
  if (comment.isLiking) return; 
  // 开始加载，显示加载状态
  comment.isLiking = true; 
  if (!profile.value?.id) {
    ElMessage.warning('请先登录');
    return;
  }

  try {
    if (comment.isLiked) {
      await deleteUserLike({
        userId: profile.value.id,
        contentId: comment.id,
        contentType: 'comment'
      });
      comment.likeCount--;
      comment.isLiked = false;
      ElMessage.info('取消点赞');
    } else {
      await createUserLike({
        userId: profile.value.id,
        targetUserId: comment.userId,
        contentId: comment.id,
        contentType: 'comment'
      });
      comment.likeCount++;
      comment.isLiked = true;
      ElMessage.success('点赞成功');
    }
  } catch (error) {
    console.error('评论点赞操作失败:', error);
    ElMessage.error('操作失败');
  } finally {
    // 加载结束，隐藏加载状态
    comment.isLiking = false; 
  }
};

const handleReplyLike = async (reply) => {
  // 如果正在加载，直接返回，防止重复点击
  if (reply.isLiking) return; 
  // 开始加载，显示加载状态
  reply.isLiking = true; 
  if (!profile.value?.id) {
    ElMessage.warning('请先登录');
    return;
  }

  try {
    if (reply.isLiked) {
      await deleteUserLike({
        userId: profile.value.id,
        contentId: reply.id,
        contentType: 'comment'
      });
      reply.likeCount--;
      reply.isLiked = false;
      ElMessage.info('取消点赞');
    } else {
      await createUserLike({
        userId: profile.value.id,
        targetUserId: reply.userId,
        contentId: reply.id,
        contentType: 'comment'
      });
      reply.likeCount++;
      reply.isLiked = true;
      ElMessage.success('点赞成功');
    }
  } catch (error) {
    console.error('回复点赞操作失败:', error);
    ElMessage.error('操作失败');
  } finally {
    // 加载结束，隐藏加载状态
    reply.isLiking = false; 
  }
};

const handleLike = async () => {
  // 如果正在加载，直接返回，防止重复点击
  if (isLiking.value) return; 
  // 开始加载，显示加载状态
  isLiking.value = true; 
  try {
    if (isLiked.value) {
      await deleteUserLike({
        userId: profile.value.id,
        contentId: article.value.id,
        contentType: 'article'
      });
      article.value.likeCount--;
      isLiked.value = false;
      ElMessage.info('取消点赞');
    } else {
      await createUserLike({
        userId: profile.value.id,
        targetUserId: author.value.id,
        contentId: article.value.id,
        contentType: 'article'
      });
      article.value.likeCount++;
      isLiked.value = true;
      ElMessage.success('点赞成功');
    }
  } catch (error) {
    ElMessage.error('操作失败');
  } finally {
    // 加载结束，隐藏加载状态
    isLiking.value = false; 
  }
};

const handleFavorite = async (folderId) => {
  isFavoriteFoldersLoading.value = true; // 开始加载收藏夹列表，显示加载状态
  try {
    const folder = favoriteFolders.value.find(f => f.id === folderId); // 找到点击的收藏夹
    if (folder.isFavorited) {
      // 取消收藏操作
      await deleteUserFavorite({
        userId: profile.value.id,
        contentId: article.value.id,
        contentType: 'article',
        folderId: folderId
      });
      article.value.favoriteCount--; // 文章收藏数量减1
      folder.isFavorited = false; // 更新该收藏夹的收藏状态为未收藏
      folder.contentCount--; // 收藏夹的收藏数量减1
      ElMessage.info('取消收藏'); // 提示用户取消收藏成功
    } else {
      // 收藏操作
      await createUserFavorite({
        userId: profile.value.id,
        contentId: article.value.id,
        contentType: 'article',
        folderId: folderId
      });
      article.value.favoriteCount++; // 文章收藏数量加1
      folder.isFavorited = true; // 更新该收藏夹的收藏状态为已收藏
      folder.contentCount++; // 收藏夹的收藏数量减1
      ElMessage.success('收藏成功'); // 提示用户收藏成功
    }
    // 更新整体收藏状态，检查是否有任何收藏夹处于收藏状态
    isFavorited.value = favoriteFolders.value.some(f => f.isFavorited);


  } catch (error) {
    ElMessage.error('操作失败'); // 提示用户操作失败
  } finally {
    isFavoriteFoldersLoading.value = false; // 加载完成，隐藏加载状态
  }
};

const handleFollow = async () => {
  if (!profile.value?.id) {
    ElMessage.warning('请先登录');
    return;
  }
  // 添加身份校验，防止自己关注自己
  if (author.id === profile.value.id) {
    ElMessage.warning('不能关注自己');
    return;
  }
  try {
    if (isFollowed.value) {
      await unfollowUser({
        followerId: profile.value.id,
        followingId: author.value.id
      });
      author.value.followerCount--;
      isFollowed.value = false;
      ElMessage.info('取消关注');
    } else {
      await followUser({
        followerId: profile.value.id,
        followingId: author.value.id
      });
      author.value.followerCount++;
      isFollowed.value = true;
      ElMessage.success('关注成功');
    }
  } catch (error) {
    ElMessage.error('操作失败');
  }
};

const scrollToTop = () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
};

const scrollToBottom = () => {
  window.scrollTo({
    top: document.documentElement.scrollHeight,
    behavior: 'smooth'
  });
};

onMounted(async () => {
  try {
    const response = await findArticleById(articleId.value);
    article.value = response.data;
    
    // 获取作者信息
    if (article.value.userId) {
      const userResponse = await findUserById(article.value.userId);
      author.value = userResponse.data;
      
      // 检查是否点赞、收藏和关注
      if (profile.value.id) {
        const [likeResponse, favoriteResponse, followResponse, foldersResponse] = await Promise.all([
          checkIsLiked(profile.value.id, article.value.id),
          checkIsFavorite(profile.value.id, article.value.id),
          checkIsFollowing(profile.value.id, author.value.id),
          getAllFavoriteFolders(profile.value.id)
        ]);
        isLiked.value = likeResponse.data;
        isFavorited.value = favoriteResponse.data;
        isFollowed.value = followResponse.data;
        
        // 获取收藏夹列表并检查每个收藏夹的收藏状态
        const folders = foldersResponse.data;
        const folderFavoriteChecks = await Promise.all(
          folders.map(folder => 
            isFolderFavorite(profile.value.id, article.value.id, folder.id)
          )
        );
        
        favoriteFolders.value = folders.map((folder, index) => ({
          ...folder,
          isFavorited: folderFavoriteChecks[index].data
        }));
      }
    }

  } catch (error) {
    console.error('获取文章详情失败:', error);
    ElMessage.error('获取文章详情失败');
  }
  commentSortDesc.value = false;
  await handleSortChange();
});


</script>

<style scoped>
.article-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
  background-color: #ffffff;
  min-height: 100vh;
}

.article-header {
  margin-bottom: 30px;
  text-align: center;
  padding-bottom: 30px;
  position: relative;
}

.article-header::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 100px;
  height: 3px;
  background: linear-gradient(to right, #409eff, #67c23a);
  border-radius: 3px;
}

.article-title {
  font-size: 2.5rem;
  color: #303133;
  font-weight: 700;
  margin-bottom: 20px;
  line-height: 1.3;
}

.article-description {
  font-size: 1.1rem;
  color: #606266;
  max-width: 800px;
  margin: 0 auto;
  line-height: 1.6;
}

.author-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 40px;
  padding: 15px 20px;
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

.author-basic {
  display: flex;
  align-items: center;
  gap: 15px;
}

.author-avatar img {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
  cursor: pointer;
}

.author-avatar img:hover {
  transform: scale(1.1);
}

.author-name {
  font-size: 1.1rem;
  font-weight: 600;
  color: #303133;
}

.follow-btn {
  color: white;
  background-color: #409eff;
  transition: all 0.3s;
}

.follow-btn.gray-background {
  background-color: #e9e9e9;  /* 已关注背景色 */
  color: #909399;
}
.follow-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
.author-card {
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}
.author-card-info {
  margin: 15px 0;
  color: #606266;
  line-height: 1.6;
}
.author-card-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
}

.author-card-header img {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  border: 3px solid #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.author-card-header h3 {
  margin: 0;
  font-size: 1.2rem;
  color: #303133;
}

.author-card-stats {
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 5px 10px;
}

.stat-label {
  font-size: 0.9rem;
  color: #909399;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 1.2rem;
  font-weight: 600;
  color: #303133;
}

.article-content-wrapper {
  margin-bottom: 40px;
}

.article-content {
  font-size: 1.1rem;
  line-height: 1.8;
  color: #303133;
}

.article-meta {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 20px;
  margin-bottom: 40px;
  padding: 15px 0;
  border-top: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #909399;
  font-size: 0.9rem;
}

.interaction-area {
  margin-top: 40px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 30px;
  margin-bottom: 40px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  background-color: #f5f7fa;
  color: #606266;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.action-btn:hover {
  transform: translateY(-3px);
  box-shadow: none; /* 去掉悬停时的阴影 */
  background-color: #f5f7fa; /* 悬停时可以添加一个淡背景色，可选 */
}

.comment-btn {
  color: #67C23A; /* 修改评论按钮文字颜色为原来的背景色 */
}

.comment-btn:hover {
  background-color: rgba(103, 194, 58, 0.1); /* 悬停时的淡背景色，可选 */
}

.like-btn {
  color: #909399;; /* 修改点赞按钮文字颜色为原来的背景色 */
  background-color: white
}
.like-btn.active {
  color: #409eff; /* 蓝色 */
}
.like-btn:hover {
  background-color: rgba(245, 108, 108, 0.1); /* 悬停时的淡背景色，可选 */
}

.favorite-btn {
  color: #E6A23C; /* 修改收藏按钮文字颜色为原来的背景色 */
}

.favorite-btn:hover {
  background-color: rgba(230, 162, 60, 0.1); /* 悬停时的淡背景色，可选 */
}

.action-btn.active {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.folder-list {
  padding: 15px;
}

.folder-list h4 {
  margin-top: 0;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  font-size: 1rem;
  color: #303133;
}

.folder-list ul {
  list-style: none;
  padding: 0;
  margin: 0;
  max-height: 300px;
  overflow-y: auto;
}

.folder-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  margin-bottom: 8px;
  border-radius: 4px;
  transition: all 0.3s;
}

.folder-item:hover {
  background-color: #f5f7fa;
  transform: translateX(5px);
}

.comments-section {
  margin-top: 40px;
  background-color: #f9f9f9;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.comments-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.comments-header h3 {
  margin: 0;
  font-size: 1.2rem;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.editor-container {
  margin-bottom: 30px;
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.editor-wrapper {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 15px;
}

.submit-comment {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 100%;
  padding: 12px;
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.submit-comment:hover {
  background-color: #337ecc;
  transform: translateY(-2px);
}

.comments-list {
  margin-top: 30px;
}

.comment-item {
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 10px;
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  border-left: 4px solid #409EFF;
}

.comment-item:hover {
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}


.comment-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
}

.reply-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
}

.comment-username {
  font-weight: 600;
  color: #303133;
  margin-right: auto;
}

.comment-time {
  font-size: 0.9rem;
  color: #909399;
}

.comment-content {
  padding: 5px 0;
  color: #606266;
  line-height: 1.6;
}

.load-more {
  text-align: center;
  margin-top: 20px;
}

.no-comments {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.float-buttons {
  position: fixed;
  right: 30px;
  bottom: 30px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.float-btn {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: white;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
}

.float-btn:hover {
  background-color: #409EFF;
  transform: translateY(-2px);
}

.float-btn:hover :deep(.t-icon) {
  color: white;
}

:deep(.t-icon) {
  font-size: 1.2rem;
  transition: color 0.3s;
}
  
@media (max-width: 768px) {
  .article-title {
    font-size: 1.8rem;
  }
  
  .article-description {
    font-size: 1rem;
  }
  
  .action-buttons {
    flex-wrap: wrap;
    gap: 15px;
  }
  
  .action-btn {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 20px;
    border: none;
    border-radius: 8px;
    background-color: transparent; /* 修改为透明背景 */
    color: #606266;
    font-size: 1rem;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s;
  }
}

/* 在<style scoped>部分的末尾添加 */
.replies-container {
  border-top: 1px solid #f0f0f0;
  margin-top: 20px;
  padding-top: 20px;
  margin-left: 40px;
}

.reply-item {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px dashed #dcdfe6; /* 可选虚线样式 */
}

.user-info {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  gap: 10px; /* 设置元素之间的间距 */
}

/* 添加样式来实现蓝色字体和鼠标悬浮效果 */
.toggle-replies {
  background: none;
  border: none;
  color: #3498db;
  cursor: pointer;
  font-size: 14px;
}

.toggle-replies:hover {
  text-decoration: underline; /* 鼠标悬浮时显示下划线 */
}

/* 新增 .comments-list 样式 */
.comments-list {
  margin-top: 30px;
}

/* 新增 .comment-header 样式 */
.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

/* 新增 .comment-username 样式 */
.comment-username {
  font-weight: 600;
  color: #303133;
  margin-right: auto;
}

/* 新增 .comment-time 样式 */
.comment-time {
  font-size: 0.9rem;
  color: #909399;
}

.action-button {
  background: none;
  border: none;
  cursor: pointer;
  gap: 8px;
}
/* 评论和回复点赞图标激活状态样式 */
.action-button .t-icon.active {
  color: #409eff; /* 蓝色 */
}
.username-hover {
  color: inherit; /* 初始颜色继承父元素 */
  cursor: pointer; /* 鼠标悬浮时显示手型 */
  transition: color 0.3s; /* 颜色变化过渡效果 */
}

.username-hover:hover {
  color: #409eff; /* 鼠标悬浮时字体变为蓝色 */
}

.time {
  color: #909399; /* 时间显示变灰 */
}

.reply-to {
  color: #909399; /* 回复二字变灰 */
}

.sort-switch {
  display: flex;
  gap: 10px;
}

.sort-switch span {
  cursor: pointer;
  padding: 2px 8px;
  border-radius: 4px;
  transition: all 0.3s;
}

.sort-switch span.active {
  background-color: #409eff;
  color: white;
}

.sort-switch span:hover {
  background-color: #e4f0ff;
  text-decoration: underline;
}

.comment-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.comment-actions {
  display: flex;
  gap: 20px;
}

.t-icon.loading {
  color: #409eff;
  /* 添加旋转动画 */
  animation: spin 1s linear infinite; 
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>
